package com.spnice.sgsms.util;

import com.spnice.sgsms.support.PDFLayoutTextStripper;
import com.spnice.sgsms.support.PdfBoxKeyWordPosition;
import com.spnice.sgsms.vo.SettingVo;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class SettingUtils {
    private static final String KEYWORD = "序号";
    private static final String ORDER_NUMBER = "序号";
    private static final String DESCRIPTION = "整定项目";
    private static final String VALUE = "定值";
    private static final String UNIT = "单位";

    public static List<SettingVo> analysisPDF(InputStream inputStream) {
        try {
            @Cleanup
            PDDocument pdDocument = PDDocument.load(inputStream);
            int numberOfPages = pdDocument.getNumberOfPages();
            Splitter splitter = new Splitter();
            splitter.setStartPage(1);
            splitter.setEndPage(numberOfPages);

            PdfBoxKeyWordPosition kwp = new PdfBoxKeyWordPosition(KEYWORD);
            List<PDDocument> pdDocumentList = splitter.split(pdDocument);
            List<List<String>> settings = new ArrayList<>();
            for (int i = 0; i < pdDocumentList.size(); i++) {
                @Cleanup
                PDDocument document = pdDocumentList.get(i);
                PDPage page = document.getPage(0);
                PDRectangle cropBox = page.getCropBox();
                // 获取关键字坐标
                List<float[]> positionList = kwp.getCoordinate(document);
                if (positionList.size() == 1) {
                    // TODO 序号|整定项目|定值|单位|备注
                    PDFTextStripper stripper = new PDFTextStripper();
                    stripper.setWordSeparator("|");
                    stripper.setSortByPosition(true);
                    String content = stripper.getText(document);
                    if (StringUtils.isBlank(content)) {
                        continue;
                    }
                    String[] contentArray = content.split(stripper.getLineSeparator());
                    // 标记是否开始读取定值条目
                    boolean flag = false;
                    List<List<String>> settingContent = new ArrayList<>(contentArray.length);
                    int dataLength = 0;
                    int orderNumberIndex = -1;
                    int descriptionIndex = -1;
                    int valueIndex = -1;
                    int unitIndex = -1;
                    for (String s : contentArray) {
                        if (StringUtils.isBlank(s)) {
                            continue;
                        }
                        List<String> lineList = Arrays.asList(s.split("\\|"));
                        if (lineList.size() == 1) {
                            continue;
                        }
                        // TODO 去掉备注、备用等内容
                        // TODO 处理序号合并的行
                        if (!flag && lineList.contains(KEYWORD)) {
                            flag = true;
                            dataLength = lineList.size();
                            int k = 0;
                            for (String lineValue : lineList) {
                                if (ORDER_NUMBER.equals(lineValue)) {
                                    orderNumberIndex = k;
                                }
                                if (DESCRIPTION.equals(lineValue)) {
                                    descriptionIndex = k;
                                }
                                if (VALUE.equals(lineValue)) {
                                    valueIndex = k;
                                }
                                if (UNIT.equals(lineValue)) {
                                    unitIndex = k;
                                }
                                k++;
                            }
                            continue;
                        }
                        if (!flag) {
                            continue;
                        }
                        int orderNumber = string2Int(lineList.get(0));
                        if (orderNumber == 0) {
                            continue;
                        }
                        lineList.set(0, orderNumber + "");
                        if (lineList.size() == 2) {
                            settingContent.add(lineList);
                        } else if (lineList.size() >= 3 && lineList.size() <= dataLength) {
                            List<String> tmpData = new ArrayList<>();
                            tmpData.add(lineList.get(orderNumberIndex));
                            tmpData.add(lineList.get(descriptionIndex));
                            if (unitIndex != -1 && lineList.size() > unitIndex) {
                                tmpData.add(lineList.get(valueIndex) + " " + lineList.get(unitIndex));
                            } else {
                                tmpData.add(lineList.get(valueIndex));
                            }
                            settingContent.add(tmpData);
                        }
                    }
                    settings.addAll(settingContent);
                } else if (positionList.size() == 2) {
                    // 序号|整定项目|定值|序号|整定项目|定值
                    PDFTextStripperByArea stripperByArea = new PDFTextStripperByArea();
                    float[] leftPosition = positionList.get(0);
                    float[] rightPosition = positionList.get(1);
                    if (Math.abs(leftPosition[0] - rightPosition[0]) > 10) {
                        log.info("不能解析的格式，页码：{}", i + 1);
                        continue;
                    }
                    // -10修正
                    int width = (int) (rightPosition[1] - leftPosition[1]);
                    stripperByArea.addRegion("left",
                            new Rectangle((int) leftPosition[1], (int) leftPosition[0], width, (int) cropBox.getHeight()));
                    stripperByArea.addRegion("right",
                            new Rectangle((int) rightPosition[1], (int) rightPosition[0], width, (int) cropBox.getHeight()));
                    stripperByArea.setWordSeparator("|");
                    stripperByArea.setSortByPosition(true);
                    stripperByArea.extractRegions(page);
                    String leftContent = stripperByArea.getTextForRegion("left");
                    String rightContent = stripperByArea.getTextForRegion("right");
                    if (StringUtils.isBlank(leftContent) || StringUtils.isBlank(rightContent)) {
                        log.info("文档第{}页数据异常", i + 1);
                        log.info("文档左列数据：{}", leftContent);
                        log.info("文档右列数据：{}", rightContent);
                        continue;
                    }
                    String[] leftContentArray = leftContent.split(stripperByArea.getLineSeparator());
                    String[] rightContentArray = rightContent.split(stripperByArea.getLineSeparator());
                    // 标记是否先按行增长
                    boolean isIncreaseByRowFirst = false;
                    List<List<String>> settingLeftContent = new ArrayList<>(leftContentArray.length);
                    List<List<String>> settingRightContent = new ArrayList<>(rightContentArray.length);

                    array2List(leftContentArray, settingLeftContent);
                    array2List(rightContentArray, settingRightContent);
                    // 判断序号是先按行递增还是先按列递增
                    // 找出size为3的连续2条记录，若不存在，不解析该定值单
                    for (int t = 0; t < settingLeftContent.size(); t++) {
                        if (settingLeftContent.get(t).size() == 3
                                && settingLeftContent.get(t + 1).size() == 3
                                && (t + 1) < settingLeftContent.size()) {
                            int orderNumber = string2Int(settingLeftContent.get(t).get(0));
                            int nextOrderNumber = string2Int(settingLeftContent.get(t + 1).get(0));
                            if (orderNumber != 0 && (orderNumber + 1) == nextOrderNumber) {
                                isIncreaseByRowFirst = true;
                            }
                            break;
                        }
                    }

                    if (isIncreaseByRowFirst) {
                        // increaseByRowFirst
                        settings.addAll(settingLeftContent);
                        settings.addAll(settingRightContent);
                    } else {
                        // TODO increaseByColumnFirst
                    }
                } else {
                    // TODO 其他情况
                }
            }
            int currentGroupNumber = 1;
            String currentGroupName = null;
            List<SettingVo> settingVos = new ArrayList<>();
            for (List<String> setting : settings) {
                if (setting.size() == 2) {
                    currentGroupNumber = Integer.parseInt(setting.get(0));
                    currentGroupName = setting.get(1);
                } else if (setting.size() == 3) {
                    SettingVo settingVo = new SettingVo();
                    settingVos.add(settingVo);
                    settingVo.setGroupOrderNumber(currentGroupNumber);
                    settingVo.setGroupName(currentGroupName);
                    settingVo.setOrderNumber(Integer.parseInt(setting.get(0)));
                    settingVo.setDescription(setting.get(1));
                    String value = setting.get(2);
                    if (value.contains(" ")) {
                        settingVo.setValue(value.substring(0, value.indexOf(" ")));
                        settingVo.setUnit(value.substring(value.indexOf(" ") + 1));
                    } else {
                        settingVo.setValue(value);
                    }
                }
            }
            return settingVos;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static int string2Int(String str) {
        if (NumberUtils.isChineseNumber(str)) {
            return NumberUtils.chineseNumToArabicNum(str);
        } else if (NumberUtils.isNumber(str)) {
            return Integer.parseInt(str);
        }
        return 0;
    }

    private static void array2List(String[] array, List<List<String>> list) {
        for (String s : array) {
            if (StringUtils.isBlank(s)) {
                continue;
            }
            List<String> lineList = Arrays.asList(s.split("\\|"));
            if (lineList.size() == 1) {
                continue;
            }
            if ("备用".equals(lineList.get(0))) {
                continue;
            }
            int orderNumber = string2Int(lineList.get(0));
            if (orderNumber == 0) {
                continue;
            }
            lineList.set(0, orderNumber + "");

            // TODO 处理序号合并的行
            list.add(lineList);
        }
    }

    public static List<List<String>> getPDFText(InputStream inputStream) {
        List<List<String>> content = new ArrayList<>();
        try {
            @Cleanup
            PDDocument pdDocument = PDDocument.load(inputStream);
            PDFTextStripper stripper = new PDFLayoutTextStripper();
            String text = stripper.getText(pdDocument);
            String[] data = text.split("\n");
            System.out.println(data.length);
            for (String datum : data) {
                if (StringUtils.isBlank(datum)) {
                    continue;
                }
                content.add(Arrays.asList(datum.replaceAll("\\s{4,}", "|").split("\\|")));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}
